/*
 * @Author: mark
 * @Date: 2024-02-18 21:10:41
 * @LastEditors: mark
 * @LastEditTime: 2024-02-25 22:10:46
 * @FilePath: /自研/RuoYi_egg/ruoyi-egg/app/service/test.js
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
const path = require("path");
const fs = require("fs");
const { default: axios } = require("axios");
const Service = require("egg").Service;
const chinaPro = [
  "中国",
  "河北",
  "山西",
  "辽宁",
  "吉林",
  "黑龙",
  "江苏",
  "浙江",
  "安徽",
  "福建",
  "江西",
  "山东",
  "河南",
  "湖北",
  "湖南",
  "广东",
  "海南",
  "四川",
  "贵州",
  "云南",
  "陕西",
  "甘肃",
  "青海",
  "台湾",
  "内蒙",
  "广西",
  "西藏",
  "宁夏",
  "新疆",
  "北京",
  "天津",
  "上海",
  "重庆",
  "香港",
  "澳门",
];

let araList = null;

/**
 * ip变数字
 * @param {*} ip
 * @returns
 */
function ipToNumber(ip) {
  let ipArray = ip.split(".");
  let number = "";
  ipArray.forEach((segment) => {
    let paddedSegment = segment.padStart(3, "0");
    number += paddedSegment;
  });
  return parseInt(number);
}

/**
 * 拆分省市
 * @param {*} area
 */
function getProCity(area) {
  let province = "";
  if (area.indexOf("黑龙江") > -1 || area.indexOf("内蒙古") > -1) {
    province = area.substr(0, 3);
  } else {
    province = area.substr(0, 2);
  }
  let areaPass = ["新疆", "广西", "宁夏", "内蒙古", "西藏"];
  if (area.indexOf("区") > -1) {
    return {
      province,
      city: area.split("市")[1],
    };
  } else {
    let check = false;
    areaPass.forEach((item) => {
      if (area.indexOf(item) > -1) {
        check = true;
      }
    });
    if (check) {
      if (area.indexOf("内蒙古") > -1) {
        return {
          province,
          city: area.substr(3) || "",
        };
      } else {
        return {
          province,
          city: area.substr(3) || "",
        };
      }
    } else {
      return {
        province,
        city: area.split("省")[1] || "",
      };
    }
  }
}

class GetIPService extends Service {
  constructor(ctx) {
    super(ctx);
    this.session = ctx.session;
    this.ResponseCode = ctx.response.ResponseCode;
    this.ServerResponse = ctx.response.ServerResponse;
    this.objUnderlineToHump = ctx.objUnderlineToHump;
    this.underlineToHump = ctx.underlineToHump;
    this.objHumpToUnderline = ctx.objHumpToUnderline;
    this.underlineToHump = ctx.underlineToHump;
    this.toInt = ctx.toInt;
    this.ctx = ctx;
    this.GenTable = ctx.model.GenTable;
    this.GenTableColumn = ctx.model.GenTableColumn;
  }

  /**
   * 读取ip地址，并将其塞入缓存
   */
  async setIp() {
    let data = fs.readFileSync(
      path.join(__dirname, "..", "utils", "ip.txt"),
      "utf-8"
    );
    data = data.split("\n");
    data = data.map((item) => {
      item = item
        .replace(/\s+/g, " ")
        .replace(/^((?:\S+\s+){1})(\S+)/, "$1$2&");
      item = item.split("& ");
      let start = item[0].split(" ");
      let end = start[1];
      start = start[0];
      let area = item[1].split(" ");
      let oper = area[1].split("/")[0];
      area = area[0];
      let detail = getProCity(area);
      return {
        start,
        sNum: ipToNumber(start),
        end,
        eNum: ipToNumber(end),
        area,
        oper,
        detail,
      };
    });
    data = data.filter((item) => chinaPro.indexOf(item.area.substr(0, 2)) > -1);
    data = data.sort((a, b) => a - b);
    araList = data;
    console.log("ip地址库存入完成\n");
  }

  /**
   * 获取ip归属地
   * @param {*} ip
   */
  getIpLocal(ip) {
    ip = ipToNumber(ip);
    let low = 0;
    let high = araList.length - 1;
    let mid;
    while (low <= high) {
      mid = Math.floor((low + high) / 2);
      if (ip < araList[mid].sNum) {
        high = mid - 1;
      } else if (ip > araList[mid].eNum) {
        low = mid + 1;
      } else {
        return {
          area: araList[mid].area,
          oper: araList[mid].oper,
          detail: araList[mid].detail,
        };
      }
    }
    return {
      area: "未匹配ip",
      oper: "未匹配ip",
      detail: {
        province: "未匹配ip",
        city: "未匹配ip",
      },
    };
  }

  /**
   * 获取路径下的所有文件
   * @param {*} folderPath
   */
  async getAllFilePathsSync(folderPath) {
    let filePaths = [];

    const files = fs.readdirSync(folderPath);

    files.forEach((file) => {
      const filePath = path.join(folderPath, file);
      const stats = fs.statSync(filePath);

      if (stats.isFile()) {
        filePaths.push(filePath);
      } else if (stats.isDirectory()) {
        const subDirFiles = getAllFilePathsSync(filePath);
        filePaths = filePaths.concat(subDirFiles);
      }
    });

    return filePaths;
  }

  /**
   * 睡眠
   * @param {*} milliseconds
   */
  sleep(milliseconds) {
    const start = new Date().getTime();
    while (new Date().getTime() - start < milliseconds) {
      // 使用while循环阻塞指定的毫秒数
    }
  }

  /**
   * 更新ip
   */
  async updateIp() {
    let data = fs.readFileSync(
      path.join(__dirname, "..", "utils", "updateIp.txt"),
      "utf-8"
    );
    data = data.split("\r\n");
    let remark = [];
    for (let i = 0; i < data.length; i++) {
      setTimeout(async () => {
        let ipData = await axios.get(
          `https://qifu-api.baidubce.com/ip/geo/v1/district?ip=${data[i]}`
        );
        if (ipData.data.code == "Success") {
          let area =
            ipData.data.data.country == "中国"
              ? ipData.data.data.prov + ipData.data.data.city
              : ipData.data.data.country;
          let ip3 = data[i].split(".").slice(0, -1).join(".");
          fs.appendFileSync(
            "C:/Users/10530/Desktop/ipCheck.txt",
            `${ip3 + ".0"} ${ip3 + ".255"} ${area} ${ipData.data.data.owner}\n`
          );
        } else {
          console.log("错误: " + ip);
        }
        console.log(i + "/" + data.length);
      }, i * 1000);
    }
    console.log(1);
  }
}

module.exports = GetIPService;
